#!/usr/bin/env python3
"""Learns about the operator once, right after setup, in a background Claude Code session: the wiki skill's
research mode reads whatever tools they have connected (calendar, GitHub, Linear, Slack…, read-only) and writes
who they are, what they are working on and who they work with into the wiki. Every call refines it afterwards
(the same skill, after a call). Aux runs this when the Set up window is finished; it is a no-op once it has run
for a wiki.

  aux-learn            # once per wiki (a marker in the wiki's .bin/)
  aux-learn --force    # again

The wiki is AUX_WIKI when set (a trial wiki, scripts/try-dev-fresh), else $AUX_HOME/wiki. The log is
$AUX_HOME/learn.log.
"""
import os
import subprocess
import sys
from pathlib import Path

# Inside an app bundle a __pycache__ write is macOS's "python3 was prevented from modifying apps" prompt.
sys.dont_write_bytecode = True
sys.path.insert(0, str(Path(__file__).resolve().parent))
import aux_context as ctx  # noqa: E402

MAX_TURNS = 30


def main():
    wiki = Path(os.environ.get("AUX_WIKI") or ctx.WIKI)
    marker = wiki / ".bin" / "learned"
    if not (wiki / "me.md").exists():
        print(f"aux-learn: no wiki at {wiki}", file=sys.stderr)
        return 1
    if marker.exists() and "--force" not in sys.argv:
        return 0
    marker.parent.mkdir(parents=True, exist_ok=True)
    marker.write_text("")
    project = ctx.project()
    prompt = (
        f"This is the first run after Aux's setup: do the wiki skill's Research mode. The wiki is at {wiki} "
        "(use that path wherever the skill says $AUX_HOME/wiki). Setup asked the operator nothing about "
        "themselves: me.md has their name, email and Tuple ids, a guess at their company from their email, and "
        "default call rules; home.md is empty. Nobody is watching this session, so ask no questions."
    )
    # The plugin and this wiki only (not claude_plugin_args, whose wiki is always $AUX_HOME/wiki).
    cmd = ["claude", "-p", "--plugin-dir", str(ctx.PLUGIN), "--add-dir", str(wiki),
           "--permission-mode", "auto", "--max-turns", str(MAX_TURNS),
           "--append-system-prompt", prompt, ctx.plugin_skill("wiki") + " research"]
    log = open(ctx.AUX / "learn.log", "ab")
    subprocess.Popen(cmd, cwd=str(project) if project.exists() else None, stdout=log, stderr=subprocess.STDOUT,
                     stdin=subprocess.DEVNULL, start_new_session=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
